package com.emergency.embackend.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.emergency.embackend.dto.UserDTO;
import com.emergency.embackend.exception.EmException;
import com.emergency.embackend.utils.JWTUtils;
import com.emergency.embackend.utils.RedisConstants;
import com.emergency.embackend.utils.TypeUtils;
import com.emergency.embackend.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author chddd
 * @description
 * @create 2024/1/27 13:15:07
 */
public class RefreshInterceptor implements HandlerInterceptor {
    private StringRedisTemplate stringRedisTemplate;

    public RefreshInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //通过请求头获取token的值
        String token = request.getHeader("token");
        //以token为key从redis中获取用户数据
        //通过配置类的注入，来获取stringRedisTemplate对象
        //判断token是否存在
        String key = RedisConstants.LOGIN_USER_KEY + token;

        if (StrUtil.isEmpty(token)) {
            //token为空,一般是登陆或者是注册，直接放行
            return true;
        }
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(key);
        //判断用户是否存在
        if (userMap.isEmpty()||!JWTUtils.checkToken(token)) {
            throw new EmException("401","token失效");
        }
        //将查询到的hash对象转换为UserDTO
        UserDTO user = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);

        //存在，则保存用户信息到ThreadLocal
        UserHolder.saveUser(user);

        //刷新token的有效期，防止在浏览过程中会突然过期
        stringRedisTemplate.expire(key, RedisConstants.LOGIN_TOKEN_TTL, TimeUnit.DAYS);
        return true;
    }

}
